from datetime import datetime
from peak.events import trellis
from wxpita import *

songdb = {
    101: ["Time's Scar", 'Yasunori Mitsuda', '2002-10-06', 'Instrumental', 8],
    102: ['Always With You', 'Divide & Create', '2006-04-12', 'Mashup', 9],
    103: ['Lavender Blue', 'Burl Ives', '1973-09-18', 'Folk', 7],
    104: ['SOS', 'Kaci Brown', '2006-11-23', 'Pop', 7],
    105: [u'\u4f20\u5947', u'\u6625\u79cb', '2007-05-03', 'Rock', 9],
}

class Song(trellis.Component):
    trellis.values(
        title = '',
        artist = '',
        release_date = wx.DateTime_Today(),
        genre = '',
        rating = 1,
    )
    index = 0

    @trellis.action
    def show(self):
        self.index += 1
        print '%d.  %s' % (self.index, self)
        print '-'*79

    def __str__(self):
        return '%s, %s, %s, %s, %s' % (repr(self.title), repr(self.artist),
            self.release_date, self.genre, self.rating)

class SongDbRetriever(trellis.Component):
    db = trellis.value(None)
    model = trellis.value(None)
    rowid = trellis.receiver(None)

    @trellis.action
    def update_model(self):
        if self.rowid is None: return
        
        row = self.db[self.rowid]
        m = self.model
        m.title, m.artist, rdate, m.genre, m.rating = row
        m.release_date = self.str2wxdatetime(rdate)

    def str2wxdatetime(self, text):
        dt = datetime.strptime(text, '%Y-%m-%d')
        return wx.DateTimeFromDMY(dt.day, dt.month, dt.year)

class Controller(trellis.Component):
    model = trellis.value(None)
    cell = trellis.value(None)

    view = None
    member = ''
    evtbinder = None

    @trellis.action
    def init(self):
        self.cell = trellis.Cells(self.model)[self.member]
        # Binding this object to the view as an event handler ensures it
        # won't be deleted until the view itself is deleted
        self.view.Bind(self.evtbinder, self)

    @trellis.action
    def update_view(self):
        self.view.SetValue(self.cell)

    def __call__(self, evt):
        "I am an event handler"
        setattr(self.model, self.member, self.view.GetValue())        

genres = 'Country', 'Rock', 'Mashup', 'Pop', 'Instrumental', 'Folk',

f = SizedFrame(sizerType='horizontal') [
    ListBox(name='lb', expand=True),
    
    SizedPanel(sizerType='form', expand=True, proportion=1) [
        StaticText(label='Title'),
        TextCtrl(name='title', expand=True),

        StaticText(label='Artist'),
        TextCtrl(name='artist', expand=True),

        StaticText(label='Release Date'),
        DatePickerCtrl(name='release_date', style='dp_dropdown'),

        StaticText(label='Genre'),
        ComboBox(name='genre', choices=genres, size=(160,-1)),

        StaticText(label='Rating'),
        SpinCtrl(name='rating', min=1, max=10, initial=1),
    ]
]

song = Song()
sdr = SongDbRetriever(db=songdb, model=song)
sdr.rowid = 101

@f.Init
def _():
    keys = songdb.keys()
    keys.sort()
    
    for i, k in enumerate(keys):
        f.lb.Append(songdb[k][0])
        f.lb.SetClientData(i, k)

    # Set up the controllers:
    Controller(view=f.title, model=song, member='title', evtbinder=wx.EVT_TEXT)
    Controller(view=f.artist, model=song, member='artist',
               evtbinder=wx.EVT_TEXT)
    Controller(view=f.release_date, model=song, member='release_date',
               evtbinder=wx.EVT_TEXT)
    Controller(view=f.genre, model=song, member='genre', evtbinder=wx.EVT_TEXT)
    Controller(view=f.rating, model=song, member='rating',
               evtbinder=wx.EVT_SPIN)

    f.lb.SetSelection(0)

@f.lb.listbox_selected
def _(evt):
    rowid = f.lb.GetClientData(f.lb.GetSelection())
    sdr.rowid = rowid
        
f.Show('Trellis Data Binding Example', (600, 500))
